#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

class Sem{
public:
	Sem(int num)
	{
		sem_init(&_sem, 0, num);
	}
	~Sem()
	{
		sem_destroy(&_sem);
	}
	void P() //P操作
	{
		sem_wait(&_sem);
	}
	void V() //V操作
	{
		sem_post(&_sem);
	}
private:
	sem_t _sem;
};

Sem sem(1); //二元信号量
int tickets = 1000;//1000张票
void* BuyTicket(void* args)
{
    std::string str = (const char*)args;
    while(1)
    {
        sem.P();
        if(tickets>0)
        {
            usleep(1000);
			std::cout <<"线程:"<< pthread_self() << " get a ticket, tickets left: " << tickets << std::endl;
            tickets--;
            sem.V();
        }
        else
        {
            sem.V();
            break;
        }
    }
    std::cout<<"购票结束"<<std::endl;
}

int main()
{
    //主线程创建4个新线程
	pthread_t tid1, tid2, tid3, tid4;
	pthread_create(&tid1, nullptr, BuyTicket, (void*)"thread 1");
	pthread_create(&tid2, nullptr, BuyTicket, (void*)"thread 2");
	pthread_create(&tid3, nullptr, BuyTicket, (void*)"thread 3");
	pthread_create(&tid4, nullptr, BuyTicket, (void*)"thread 4");
	
	pthread_join(tid1, nullptr);
	pthread_join(tid2, nullptr);
	pthread_join(tid3, nullptr);
	pthread_join(tid4, nullptr);
	return 0;
}